# conding = utf-8
import jsonpath
import yaml

from config import extract_url


def clear_extract():
    with open(extract_url, "w", encoding="utf-8") as file:
        pass

def extract_by_resp(resp:dict,extract:dict):
    print("替换前：",extract)
    #extract : 根据规则提取数据，递归
    extract_replace(resp,extract)
    #替换数据结束
    print("替换后：", extract)
    with open(extract_url,"a+",encoding="utf-8") as file:
        yaml.safe_dump(extract,file)


def extract_replace(resp:dict,extract:dict):
    '''
    根据响应的数据和提取的数据规则递归的方式替换
    :param resp:
    :param extract:
    :return:
    '''
    for k,v in extract.items():
        if isinstance(v,dict):
            extract_replace(resp,v)
        else:
            if "$." in str(v):
                value = jsonpath.jsonpath(resp, v)
                if value is False:
                    raise RuntimeError(f"根据{v}规则提取数据失败")
                extract[k] = value[0]
